package com.qian.api.ddj.util;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class SignUtils {

    public static String signOnlyValue(Map<String, String> map, String key) {
        removeNull(map);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getValue());
        }
        sb.append(key);

        return DigestUtils.md5DigestAsHex(sb.toString().getBytes());
    }

    public static Map removeNull(Map<String, String> map){
        List<String> list = new ArrayList();
        for(Map.Entry<String, String> entry : map.entrySet()) {
            if(map.get(entry.getKey())!=null){
                if(!"".equals(map.get(entry.getKey()))){
                }else{
                    list.add(entry.getKey());
                }
            }else{
                list.add(entry.getKey());
            }
        }

        for (int i = 0; i < list.size(); i++) {
            map.remove(list.get(i));
        }
        return map;

    }
    public static String sign(Map<String, String> map, String key) {
        String body = params(map) + "&key=" + key;
        return DigestUtils.md5DigestAsHex(body.getBytes());
    }

    public static boolean verifySign(Map<String, String> map, String key) {
        String s = map.remove("sign");
        String sign = sign(map, key);
        if (sign.equalsIgnoreCase(s)) {
            return true;
        }
        return false;
    }

        public static String params(Map<String, String> map) {
            StringBuilder sb = new StringBuilder();
            boolean first = true;
            for (String key : map.keySet()) {
                String value = map.get(key);
                if (!StringUtils.isEmpty(value)) {
                    if (first) {
                        first = false;
                    } else {
                        sb.append("&");
                    }
                    sb.append(key).append("=").append(value);
                }
            }
            return sb.toString();
        }

    public static String getKeyedDigest(String strSrc, String key) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(strSrc.getBytes("UTF-8"));

            String result = "";
            byte[] temp;
            temp = md5.digest(key.getBytes("UTF-8"));
            for (int i = 0; i < temp.length; i++) {
                result += Integer.toHexString((0x000000ff & temp[i]) | 0xffffff00).substring(6);
            }

            return result;

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void buildPayParams(StringBuilder sb, Map<String, String> payParams, boolean encoding) {
        List<String> keys = new ArrayList<String>(payParams.keySet());
        Collections.sort(keys);
        for (String key : keys) {
            sb.append(key).append("=");
            if (encoding) {
                sb.append(urlEncode(payParams.get(key)));
            } else {
                sb.append(payParams.get(key));
            }
            sb.append("&");
        }
        sb.setLength(sb.length() - 1);
    }

    public static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (Throwable e) {
            return str;
        }
    }
    public static String getSignParam(Map<String,String> params){
        StringBuilder buf = new StringBuilder((params.size() +1) * 10);
        buildPayParams(buf,params,false);
        String result = buf.toString();
        return result;
    }
    public static String getsign(Map<String, String> map,String key){
        StringBuilder sb= new StringBuilder();
        String[] pams= new String[0];
        pams=	map.keySet().toArray(pams);
        Arrays.sort(pams);
        for(int i=0; i<pams.length;i++){
            if(null != map.get(pams[i]) && map.get(pams[i]) != ""){
                sb.append(pams[i]).append("=").append(map.get(pams[i])).append("&");
            }
        }
        sb.setLength(sb.length()-1);
        System.out.println("请求报文："+sb);
        String sign = "";
        if (key.length() > 32) {
            //rsa
            try {
                sign = RSA.sign(sb.toString(), key);
                //System.out.println("\n sign:"+sign);
                sign = URLEncoder.encode(sign, "UTF-8");
                //System.out.println("\n sign:"+sign);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        return sign;
    }

    /**
     * 校验签名参数合法性
     * @param signType
     * @param signData
     * @throws Exception
     */
    public static boolean checkSignData(String[] signType, String[] signData) throws Exception {
        if(null == signType || signType.length <= 0)
        {
            System.out.println("签名类型不能为空");
            return false;
        }

        if(null == signData || signData.length <= 0)
        {
            System.out.println("签名内容不能为空");
            return false;
        }

        return true;
    }

    /**
     * 对接收的参数进行排序，获取待签名字符串
     * @param paramMap
     * @return
     * @throws Exception
     */
    public static String dealSignParam(Map<String, String[]> paramMap) throws Exception {
        if(null == paramMap || paramMap.isEmpty())
        {
            System.out.println("访问参数值不能为空");
        }

        StringBuffer result = new StringBuffer();
        List<String> keyList = new ArrayList<String>();
        keyList.addAll(paramMap.keySet());

        Collections.sort(keyList);

        for(int i=0; i<keyList.size(); i++)
        {
            String key = keyList.get(i);
            String[] value = paramMap.get(key);
            if(null != value && value.length > 0)
            {
                // new String(value[0].getBytes("ISO-8859-1"),"UTF-8"); 如果出现乱码情况，请使用这种方式获取参数值
                // result.append("&").append(key).append("=").append(URLDecoder.decode(value[0],"UTF-8"));
                result.append("&").append(key).append("=").append(UrlUtils.getURLDecoderString(new String(value[0])));
            }
        }

        return result.deleteCharAt(0).toString();
    }
}
